<template>
  <view class="paging-content">
    <z-paging
      v-if="dataObj.firstLoaded || dataObj.isCurrentPage"
      ref="paging"
      v-model="dataObj.dataList"
      @query="queryList"
      v-bind="$attrs"
    >
      <slot :dataList="dataObj.dataList"></slot>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { PropType, reactive, ref, watch } from "vue";
import * as swiperApi from "@/api/swiperApi";
const paging = ref();
interface requestConfigType {
  requstUrl: string;
  params: Object;
}
const dataObj = reactive({
  dataList: [],
  firstLoaded: false, // 当前组件是否已经加载过了
  isCurrentPage: false // 是否滚动到当前页
});
const props = defineProps({
  tabIndex: {
    type: String,
    required: true
  },
  currentIndex: {
    type: String,
    required: true
  },
  requestConfig: {
    type: Object as PropType<requestConfigType>,
    required: true
  }
});

// 接口请求
function queryList(pageNo: number, pageSize: number) {
  const params = {
    ...props.requestConfig.params,
    pageNum: pageNo,
    pageSize: pageSize
  };
  swiperApi[props.requestConfig.requstUrl](params)
    .then((res) => {
      paging.value.complete(res.data.data);
      dataObj.firstLoaded = true;
    })
    .catch((err) => {
      paging.value.complete(false);
    });
}

watch(
  () => props.currentIndex,
  (newVal) => {
    if (newVal === props.tabIndex) {
      // 懒加载，当滑动到当前的item时，才去加载
      if (!dataObj.firstLoaded) {
        // 这里需要延迟渲染z-paging的原因是为了避免在一些平台上立即渲染可能引发的底层报错问题
        setTimeout(() => {
          dataObj.isCurrentPage = true;
        }, 100);
      }
    }
  },
  {
    immediate: true
  }
);
</script>

<style lang="scss" scoped>
.paging-content {
  height: 100%;
  background-color: yellow;
}
</style>
